package com.rongshu.view.home.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.clickableSpan.ExPandableMovementMethod;
import com.rongshu.utils.clickableSpan.SpanableClickable;
import com.rongshu.view.home.entity.ReplyInfo;

import java.util.List;

public class CommentLiearLayout extends LinearLayout {
    private static final String tag = CommentLiearLayout.class.getSimpleName();
    private int startColor;
    private int replyColor;
    private int endColor;
    private int contentColor;
    private int defaultItemCount;//一开始展示的条目数
    private String expandText;//待展开显示的文字
    private String hideText;//待隐藏显示的文字
    private boolean useDefaultBottom;//是否使用默认的底部，默认为true使用默认的底部
    private boolean hasBottom;//是否已经有底部，默认为false，没有
    private View bottomView;
    private TextView tvTip;

    private boolean isExpand = false;//是否是展开状态，默认是隐藏
    //view
    private View view = null;
    private TextView txtView = null;

    //测试
    private List<ReplyInfo> replyInfoList = null;

    public CommentLiearLayout(Context context) {
        this(context, null);
    }

    public CommentLiearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
    }

    /**
     * 获取自定义属性
     */
    private void initAttrs(@Nullable AttributeSet attrs) {
        TypedArray typeArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.CommentLiearLayout, 0, 0);
        try {
            startColor = typeArray.getColor(R.styleable.CommentLiearLayout_startColor, getResources().getColor(R.color.color_3cc051));
            replyColor = typeArray.getColor(R.styleable.CommentLiearLayout_replyColor, getResources().getColor(R.color.color_c5c5c5));
            endColor = typeArray.getColor(R.styleable.CommentLiearLayout_endColor, getResources().getColor(R.color.color_3cc051));
            contentColor = typeArray.getColor(R.styleable.CommentLiearLayout_contentColor, getResources().getColor(R.color.color_2c2c2c));
            defaultItemCount = typeArray.getInt(R.styleable.CommentLiearLayout_defaultItemCount, 2);
            expandText = typeArray.getString(R.styleable.CommentLiearLayout_expandText);
            hideText = typeArray.getString(R.styleable.CommentLiearLayout_hideText);
            useDefaultBottom = typeArray.getBoolean(R.styleable.CommentLiearLayout_useDefaultBottom, true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            typeArray.recycle();
        }
        setOrientation(VERTICAL);
    }

    /**
     * add View
     */
    public void setRepleyList(List<ReplyInfo> repleyList) {
        if (repleyList == null) {
            return;
        }
        this.replyInfoList = repleyList;
        //清空views
        removeAllViews();
        //add view
        for (int i = 0; i < replyInfoList.size(); i++) {
            View view = getView(replyInfoList, i);
//            addView(view, i, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            addItem(view);
        }
    }

    /**
     * single view create
     */
    private View getView(List<ReplyInfo> replyInfos, int position) {
        view = LayoutInflater.from(getContext()).inflate(R.layout.comment_item_view, null, false);
        txtView = view.findViewById(R.id.txtView);
        //ReplyInfo
        ReplyInfo replyInfo = replyInfos.get(position);
        //创建富文本
        SpannableStringBuilder builder = new SpannableStringBuilder();
        if (!TextUtils.isEmpty(replyInfo.getStartUser())) {
            builder.append(clickableSpan(replyInfos, position, true));
            builder.append(": ");
        }
        if (!TextUtils.isEmpty(replyInfo.getEndUser())) {
            SpannableString spannableString = new SpannableString(" 回复 ");
            spannableString.setSpan(new ForegroundColorSpan(replyColor), 1, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.append(spannableString);
            builder.append(clickableSpan(replyInfos, position, false));
        }

        String content = replyInfo.getContent();
        builder.append(content);
        txtView.setText(builder);
        final ExPandableMovementMethod exPandableMovementMethod = new ExPandableMovementMethod();
        txtView.setMovementMethod(exPandableMovementMethod);
        return view;
    }

    /**
     * 可点击文字
     */
    private SpannableString clickableSpan(List<ReplyInfo> replyInfos, int position, final boolean isStart) {
        SpannableString spannableString = null;
        String startName = null, endName = null;
        //ReplyInfo
        ReplyInfo replyInfo = replyInfos.get(position);
        startName = replyInfo.getStartUser();
        endName = replyInfo.getEndUser()+" ";
        //deal
        spannableString = new SpannableString(isStart ? startName : endName);
        spannableString.setSpan(new SpanableClickable(isStart ? startColor : endColor,
                                        getResources().getColor(R.color.transparent)) {
                                    @Override
                                    public void onClick(View widget) {
                                        //listener
                                    }
                                },
                0, isStart ? startName.length() : endName.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }


    /**
     * 渲染完成时初始化默认底部view
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        findViews();
    }

    /**
     * 初始化底部view
     */
    private void findViews() {
        bottomView = View.inflate(getContext(), R.layout.item_ell_bottom, null);
        tvTip=bottomView.findViewById(R.id.tvTip);
        bottomView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
            }
        });
    }

    @Override
    public void setOrientation(int orientation) {
        if (LinearLayout.HORIZONTAL == orientation) {
            throw new IllegalArgumentException("ExpandableTextView only supports Vertical Orientation.");
        }
        super.setOrientation(orientation);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int childCount = getChildCount();
        Log.i(tag, "childCount: " + childCount);
        justToAddBottom(childCount);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 判断是否要添加底部
     *
     * @param childCount
     */
    private void justToAddBottom(int childCount) {
        if (childCount > defaultItemCount) {
            if (useDefaultBottom && !hasBottom) {
                //要使用默认底部,并且还没有底部
                addView(bottomView);//添加底部
                hide();
                hasBottom = true;
            }
        }
    }

    public void addItem(View view) {
        if (!useDefaultBottom) {
            //如果不使用默认底部
            addView(view);
            int childCount = getChildCount();
            if (childCount > defaultItemCount) {
                hide();
            }
            return;
        }

        //使用默认底部
        if (!hasBottom) {
            //如果还没有底部
            addView(view);
        } else {
            int childCount = getChildCount();
            addView(view, childCount - 1);//插在底部之前
        }
        refreshUI(view);
    }

    /**
     * 展开
     */
    private void expand() {
        for (int i = defaultItemCount; i < getChildCount(); i++) {
            //从默认显示条目位置以下的都显示出来
            View view = getChildAt(i);
            view.setVisibility(VISIBLE);
        }
    }

    /**
     * 收起
     */
    private void hide() {
        int endIndex = useDefaultBottom ? getChildCount() - 1 : getChildCount();//如果是使用默认底部，则结束的下标是到底部之前，否则则全部子条目都隐藏
        for (int i = defaultItemCount; i < endIndex; i++) {
            //从默认显示条目位置以下的都隐藏
            View view = getChildAt(i);
            view.setVisibility(GONE);
        }
    }

    /**
     * 刷新UI
     *
     * @param view
     */
    private void refreshUI(View view) {
        int childCount = getChildCount();
        if (childCount > defaultItemCount) {
            if (childCount - defaultItemCount == 1) {
                //刚超过默认，判断是否要添加底部
                justToAddBottom(childCount);
            }
            view.setVisibility(GONE);//大于默认数目的先隐藏
        }
    }

    public void toggle() {
        if (isExpand) {
            hide();
            tvTip.setText(expandText);
        } else {
            expand();
            tvTip.setText(hideText);
        }
        isExpand = !isExpand;

        //回调
        if (mStateListener != null) {
            mStateListener.onStateChanged(isExpand);
        }
    }


    private OnStateChangeListener mStateListener;

    /**
     * 定义状态改变接口
     */
    public interface OnStateChangeListener {
        void onStateChanged(boolean isExpanded);
    }

    public void setOnStateChangeListener(OnStateChangeListener mListener) {
        this.mStateListener = mListener;
    }


    public void setOnItemClickListener(final OnItemClickListener listener) {
        int endIndex = useDefaultBottom ? getChildCount() - 1 : getChildCount();//如果是使用默认底部，则结束的下标是到底部之前
        for (int i = 0; i < endIndex; i++) {
            View view = getChildAt(i);
            final int position = i;
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(v, position);
                }
            });
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }
}
